<template>
  <view class="address-edit">
    <view class="form-group">
      <!-- 联系人 -->
      <view class="form-item">
        <text class="label">收货人</text>
        <input 
          class="input" 
          type="text" 
          v-model="formData.receiverName" 
          placeholder="请输入收货人姓名"
        />
      </view>
      
      <!-- 手机号 -->
      <view class="form-item">
        <text class="label">手机号码</text>
        <input 
          class="input" 
          type="number" 
          maxlength="11" 
          v-model="formData.phoneNumber" 
          placeholder="请输入手机号码"
        />
      </view>
      
      <!-- 所在地区 -->
      <view class="form-item" @click="showRegionPicker">
        <text class="label">所在地区</text>
        <view class="region-picker">
          <text v-if="formData.regionText" class="region-text">
            {{formData.regionText}}
          </text>
          <text v-else class="placeholder">请选择所在地区</text>
          <text class="arrow">></text>
        </view>
      </view>
      
      <!-- 详细地址 -->
      <view class="form-item">
        <text class="label">详细地址</text>
        <textarea 
          class="textarea" 
          v-model="formData.detailedAddress" 
          placeholder="请输入详细地址信息，如道路、门牌号、小区、楼栋号、单元等"
        />
      </view>
    </view>
    
    <!-- 设为默认 -->
    <view class="form-group">
      <view class="switch-item">
        <text>设为默认收货地址</text>
        <switch 
          :checked="formData.isDefault" 
          @change="handleDefaultChange" 
          color="#07c160"
        />
      </view>
    </view>
    
    <!-- 底部按钮 -->
    <view class="footer">
      <button class="save-btn" @click="handleSave">保存</button>
    </view>
    
    <!-- 地区选择器弹窗 -->
    <uni-popup ref="regionPopup" type="bottom">
      <view class="region-popup">
        <view class="popup-header">
          <text class="cancel" @click="closeRegionPicker">取消</text>
          <text class="title">选择地区</text>
          <text class="confirm" @click="confirmRegion">确定</text>
        </view>
        <view class="region-tabs">
          <text 
            class="tab-item" 
            :class="{ active: currentLevel === 0 }"
            @click="switchTab(0)"
          >{{selectedRegions[0]?.areaName || '请选择'}}</text>
          <text 
            class="tab-item" 
            :class="{ active: currentLevel === 1 }"
            v-if="selectedRegions[0]"
            @click="switchTab(1)"
          >{{selectedRegions[1]?.areaName || '请选择'}}</text>
          <text 
            class="tab-item" 
            :class="{ active: currentLevel === 2 }"
            v-if="selectedRegions[1]"
            @click="switchTab(2)"
          >{{selectedRegions[2]?.areaName || '请选择'}}</text>
        </view>
        <scroll-view class="region-list" scroll-y>
          <view 
            class="region-item"
            :class="{ active: item.areaId === selectedRegions[currentLevel]?.areaId }"
            v-for="item in currentRegionList"
            :key="item.areaId"
            @click="selectRegion(item)"
          >
            {{item.areaName}}
          </view>
        </scroll-view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import uniPopup from '@dcloudio/uni-ui/lib/uni-popup/uni-popup.vue'
import { userApi, systemApi } from '@/api'

export default {
  components: {
    uniPopup
  },
  data() {
    return {
      addressId: '', // 添加 addressId
      formData: {
        receiverName: '',
        phoneNumber: '',
        regionText: '', // 显示文本
        provinceCode: '', // 省份ID
        provinceName: '', // 省份名称
        cityCode: '', // 城市ID
        cityName: '',
        districtCode: '', // 区县ID
        districtName: '', // 区县名称
        detailedAddress: '',
        isDefault: false
      },
      regionList: [], // 完整的地区数据
      currentLevel: 0, // 当前选择层级：0-省、1-市、2-区
      selectedRegions: [null, null, null], // 已选择的地区
      currentRegionList: [], // 当前显示的地区列表
    }
  },
  computed: {
    // 计算省市区的完整地址文本
    computedRegionText() {
      const { provinceName, cityName, districtName } = this.formData
      return [provinceName, cityName, districtName].filter(Boolean).join(' ')
    }
  },
  watch: {
    // 监听计算属性的变化，更新formData中的regionText
    computedRegionText: {
      handler(newVal) {
        this.formData.regionText = newVal
      },
      immediate: true
    }
  },
  async onLoad(options) {
    if (options.id) {
      this.addressId = options.id
      await this.getAddressDetail()
    }
    this.getRegionList()
  },
  methods: {
    // 获取地址详情
    async getAddressDetail() {
      try {
        const res = await userApi.getAddressDetail(this.addressId)
        this.formData = {
          ...res,
          regionText: [res.provinceName, res.cityName, res.districtName].filter(Boolean).join(' ')
        }
        // 设置已选择的地区
        this.selectedRegions = [
          { areaId: res.provinceCode, areaName: res.provinceName },
          { areaId: res.cityCode, areaName: res.cityName },
          { areaId: res.districtCode, areaName: res.districtName }
        ]
      } catch (error) {
        console.error('获取地址详情失败:', error)
        uni.showToast({
          title: '获取地址详情失败',
          icon: 'none'
        })
      }
    },
    // 获取地区数据
    async getRegionList() {
      try {
        // 这里替换为你的实际接口调用
        const result = await systemApi.areaCode()
        this.regionList = result
        this.currentRegionList = result
      } catch (error) {
        console.error('获取地区列表失败:', error)
      }
    },


    showRegionPicker() {
      this.$refs.regionPopup.open()
    },

    closeRegionPicker() {
      this.$refs.regionPopup.close()
    },

    // 切换省市区选项卡
    switchTab(level) {
      this.currentLevel = level
      this.updateRegionList()
    },

    // 更新当前显示的地区列表
    updateRegionList() {
      if (this.currentLevel === 0) {
        this.currentRegionList = this.regionList
      } else if (this.currentLevel === 1 && this.selectedRegions[0]) {
        this.currentRegionList = this.selectedRegions[0].children || []
      } else if (this.currentLevel === 2 && this.selectedRegions[1]) {
        this.currentRegionList = this.selectedRegions[1].children || []
      }
    },

    // 选择地区
    selectRegion(region) {
      this.selectedRegions[this.currentLevel] = region
      // 清空后续选择
      for (let i = this.currentLevel + 1; i < 3; i++) {
        this.selectedRegions[i] = null
      }
      
      // 如果有下级地区，自动进入下一级选择
      if (region.children?.length > 0 && this.currentLevel < 2) {
        this.currentLevel++
        this.updateRegionList()
      }
    },

    // 确认选择
    confirmRegion() {
      if (!this.selectedRegions[0]) {
        return uni.showToast({
          title: '请选择省份',
          icon: 'none'
        })
      }
      if (!this.selectedRegions[1]) {
        return uni.showToast({
          title: '请选择城市',
          icon: 'none'
        })
      }
      if (!this.selectedRegions[2]) {
        return uni.showToast({
          title: '请选择区县',
          icon: 'none'
        })
      }

      // 更新表单数据
      this.formData.provinceCode = this.selectedRegions[0].areaId
      this.formData.provinceName = this.selectedRegions[0].areaName
      this.formData.cityCode = this.selectedRegions[1].areaId
      this.formData.cityName = this.selectedRegions[1].areaName
      this.formData.districtCode = this.selectedRegions[2].areaId
      this.formData.districtName = this.selectedRegions[2].areaName
      this.formData.regionText = [
        this.selectedRegions[0].areaName,
        this.selectedRegions[1].areaName,
        this.selectedRegions[2].areaName
      ].join(' ')
      this.closeRegionPicker()
    },

    handleDefaultChange(e) {
      this.formData.isDefault = e.detail.value
    },
    
    async handleSave() {
      // 表单验证
      if (!this.formData.receiverName) {
        return uni.showToast({
          title: '请输入收货人姓名',
          icon: 'none'
        })
      }
      if (!this.formData.phoneNumber) {
        return uni.showToast({
          title: '请输入手机号码',
          icon: 'none'
        })
      }
      if (!this.formData.regionText) {
        return uni.showToast({
          title: '请选择所在地区',
          icon: 'none'
        })
      }
      if (!this.formData.detailedAddress) {
        return uni.showToast({
          title: '请输入详细地址',
          icon: 'none'
        })
      }
      
      try {
        // 根据是否有addressId判断是新增还是更新
        if (this.addressId) {
          // 更新地址
          this.formData.id = this.addressId
          await userApi.updateAddress(this.formData,this.addressId)
        } else {
          // 新增地址
          await userApi.saveAddress(this.formData)
        }

        uni.showToast({
          title: this.addressId ? '更新成功' : '新增成功',
          icon: 'success',
          success: () => {
            setTimeout(() => {
              uni.navigateBack()
            }, 1500)
          }
        })
      } catch (error) {
        console.error(error)
        uni.showToast({
          title: this.addressId ? '更新失败' : '新增失败',
          icon: 'none'
        })
      }
    }
  }
}
</script>

<style>
.address-edit {
  min-height: 100vh;
  background: #f8f8f8;
  padding-bottom: 120rpx;
}

.form-group {
  margin-top: 20rpx;
  background: #fff;
  padding: 0 30rpx;
}

.form-item {
  display: flex;
  padding: 30rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
}

.form-item:last-child {
  border-bottom: none;
}

.label {
  width: 160rpx;
  font-size: 28rpx;
  color: #333;
  padding-top: 6rpx;
}

.input {
  flex: 1;
  font-size: 28rpx;
  color: #333;
}

.textarea {
  flex: 1;
  height: 160rpx;
  font-size: 28rpx;
  color: #333;
}

.region-picker {
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.region-text {
  font-size: 28rpx;
  color: #333;
}

.placeholder {
  font-size: 28rpx;
  color: #999;
}

.arrow {
  color: #ccc;
  font-size: 28rpx;
}

.switch-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx 0;
  font-size: 28rpx;
  color: #333;
}

.footer {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  padding: 20rpx;
  background: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.save-btn {
  background: var(--primary-color);
  color: #fff;
  border-radius: 44rpx;
  font-size: 32rpx;
  height: 88rpx;
  line-height: 88rpx;
}

.save-btn:active {
  opacity: 0.9;
}

/* 地区选择器样式 */
.region-popup {
  background: #fff;
  border-radius: 24rpx 24rpx 0 0;
  padding-bottom: env(safe-area-inset-bottom);
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f5f5f5;
}

.popup-header .title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.popup-header .cancel,
.popup-header .confirm {
  font-size: 28rpx;
  padding: 10rpx;
}

.popup-header .cancel {
  color: #999;
}

.popup-header .confirm {
  color: var(--primary-color);
}

.region-tabs {
  display: flex;
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid #f5f5f5;
}

.region-tabs .tab-item {
  font-size: 28rpx;
  color: #666;
  margin-right: 40rpx;
  position: relative;
  padding: 10rpx 0;
}

.region-tabs .tab-item.active {
  color: var(--primary-color);
  font-weight: bold;
}

.region-tabs .tab-item.active::after {
  content: '';
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  height: 4rpx;
  background: var(--primary-color);
  border-radius: 2rpx;
}

.region-list {
  height: 600rpx;
  padding: 0 30rpx;
}

.region-item {
  height: 88rpx;
  line-height: 88rpx;
  font-size: 28rpx;
  color: #333;
  border-bottom: 1rpx solid #f5f5f5;
}

.region-item.active {
  color: var(--primary-color);
}
</style> 